package com.github.xzb617.controller;

import com.github.xzb617.client.flow.core.FlowProperties;
import com.github.xzb617.storage.api.StorageService;
import com.github.xzb617.storage.api.dto.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RefreshScope
@RestController
public class UserController {

    @Value("${server.port}")
    private Integer port;
    @Value("${app.name}")
    private String appName;

    private final FlowProperties flowProperties;

    private final StorageService storageService;

    public UserController(FlowProperties flowProperties, StorageService storageService) {
        this.flowProperties = flowProperties;
        this.storageService = storageService;
    }

    @GetMapping("/getUser")
    public ResponseEntity getUser(@RequestParam(required = false, defaultValue = "default_uid") String uid) {
        Map<String, String> user = new HashMap<>(3);
        user.put("name", "service-user");
        user.put("port", String.valueOf(port));
        user.put("appName", appName);
        user.put("uid", uid);
        user.put("flow", flowProperties.toString());
        return ResponseEntity.ok(user);
    }

    @GetMapping("/reduce")
    public ResponseEntity reduce(@RequestParam("uid") String uid, @RequestParam("count") Integer count, @RequestHeader(value = "gk-header-transfer-token", required = false) String token) {
        Result result = this.storageService.reduce(uid, count);
        String info = appName + ":" + port + " ===>>> ";
        String message = result.getMessage();
        System.out.println("token: " + token);
        return ResponseEntity.status(HttpStatus.OK).body(info + message);
    }

}
